// pages/needHelp/handle.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"

const app = getApp()
// 录音管理器
const recorderManager = wx.getRecorderManager()
// 声音播放管理器
const audioPlayer = wx.createInnerAudioContext();

Page({

  /**
   * 预约被志愿者接受
   */

  /**
   * 页面的初始数据
   */
  data: {
    triggered: false,
    // 上锁
    is_recording: false,
    // 是否发送消息
    ifSendMsgRecord: false,
    // 是否播放的是聊天音频
    isPlayingMsg: false,
    // 是否播放的是预约音频
    isPlayingAppointment: false,
    // 已录音频长度
    audioLengthRecord: 0,
    showCancelSendRecord: false,
    sendMsgBtnTextRecord: "按住说话",
    cancelTipTextRecord: "滑动到此处松手取消发送",
    // 该请求的页面
    nextPage: 1,
    // 一页的条数
    pageSize: 30,
    chatMsgList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 预约消息数据
    this.id = options.id
    this.content = API.FILE_DOWNLOAD + "?fileName=" + options.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_APPOINTMENT
    this.handleUserOpenId = options.handleUserOpenId

    // 获取页面高度，用户信息
    this.data.height = wx.getSystemInfoSync().windowHeight

    // 录音开始的回调函数
    recorderManager.onStart((res) => {
      console.log("录音开始")
    })

    // 录音停止的回调函数
    recorderManager.onStop((res) => {
      const that = this
      console.log("判断是否发送录音")
      clearInterval(this.data.audioPercentageInterval)
      // 重值状态
      this.setData({
        showCancelSendRecord: false,
        audioLengthRecord: 0,
        sendMsgBtnTextRecord: "按住说话",
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })

      //此时先判断是否需要发送录音
      if (this.data.ifSendMsgRecord == false) {
        console.log("不发送录音*********")
        return
      }

      console.log("发送录音*********")
      this.setData({
        // 重置状态
        ifSendMsgRecord: false
      })

      const duration = res.duration
      console.log(duration)
      //对录音时长进行判断，少于2s的不进行发送，并做出提示
      if (duration < 2000) {
        console.log("录音时间太短")
        // TODO 语音提示 录音时间太短小于两秒，请长按录音
        app.textToSpeech('录音时间太短，请长按录音').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
      } else {
        //进行语音发送
        that.sendChatMsg(res.tempFilePath, duration).then((res) => {
          console.log(res)
          console.log(that.data.chatMsgList)
          console.log(that.data.toMsgIndex)
          // TODO 语音提示 发送成功
          app.textToSpeech('发送成功').then((res) => {
            audioPlayer.src = res
            audioPlayer.play()
          })
        }).catch((err) => {
          console.log(err)
          // TODO 语音提示 发送失败，请检查网络后重试
          app.textToSpeech('发送失败，请稍后重试').then((res) => {
            audioPlayer.src = res
            audioPlayer.play()
          })
        })
      }
    })

    // 自然播放完后触发
    audioPlayer.onEnded(() => {
      if (this.data.isPlayingMsg == true) {
        console.log("聊天音频自然播放结束")
        // 聊天音频
        var list = this.data.chatMsgList
        for (let index = 0; index < list.length; index++) {
          list[index].playing = false
        }
        this.data.isPlayingMsg = false,
        this.setData({
          chatMsgList: list
        })
      } else {
        console.log("自然播放结束")
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.data.nextPage = 1
    // 加载最近的10条聊天消息
    this.loadMsg()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    audioPlayer.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("h-handle----------------------------------onUnload")
    // audioPlayer.destroy()
  },

  // TODO 发送聊天消息
  sendChatMsg: function(tempFilePath, duration) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        header: API.REQUEST_HEADER,
        url: API.FILE_UPLOAD,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          fileProp: API.fILE_PROP_CHAT
        },
        success: function(res) {
          const result = JSON.parse(res.data)
          console.log(result)
          const id = app.globalData.openId + API.SEPARATOR + Date.now()
          if (result.code == 20000) {
            requestUtil.post(API.SEND_CHAT_MSG, {
              "id": id,
              "createTime": new Date().format(),
              "msgType": "audio",
              "content": result.data.fileName,
              "duration": Math.ceil(duration),
              "fromUserOpenId": app.globalData.openId,
              "toUserOpenId": that.handleUserOpenId,
              "appointmentId": that.id,
            }).then(res => {
              let list = that.data.chatMsgList;
              list.push({
                "side": 'right',
                "msgLength": Math.floor(duration / 1000),
                "playing": false,
                "id": id,
                "content": API.FILE_DOWNLOAD + "?fileName=" + result.data.fileName + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT,
              })
              that.setData({
                toMsgIndex: 'msg' + String(list.length - 1),
                chatMsgList: list
              })
              resolve(res)
            }).catch(err => {
              reject(err)
            })
          } else {
            reject("上传失败，所以发送失败")
          }
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
  },


  /**
   * 发送语音消息相关
   */
  // 手指按下
  handleRecordStart: function(e) {

    if (this.data.is_recording == false) {
      console.log("++++++++++++++++++++按下按钮")
      audioPlayer.stop()
      if (this.data.isPlayingMsg == true) {
        console.log("结束聊天音频播放")
        // 聊天音频
        var list = this.data.chatMsgList
        for (let index = 0; index < list.length; index++) {
          list[index].playing = false
        }
        this.data.isPlayingMsg = false,
          this.setData({
            chatMsgList: list
          })
      }

      wx.vibrateLong()

      // TODO 语音提示 开始录音
      // app.textToSpeech('开始录音').then((res) => {
      //   audioPlayer.src = res
      //   audioPlayer.play()
      // })

      clearInterval(this.data.audioPercentageInterval)
      this.setData({
        audioLengthRecord: 0,
        is_recording: true, // 开始录音标志
        ifSendMsgRecord: true, // 默认发送录音
        startPointY: e.touches[0].clientY, //记录第一个触摸点的Y坐标信息
        showCancelSendRecord: true,
        sendMsgBtnTextRecord: "松开发送"
      })
      // 设置录音参数并开始录音
      console.log("录制聊天消息")
      recorderManager.start({
        duration: 60000,
        format: "mp3"
      });

      this.data.audioPercentageInterval = setInterval(() => {
        const audioLengthRecord = this.data.audioLengthRecord + 1
        this.setData({
          audioLengthRecord: audioLengthRecord
        })
      }, 1000)
    }
  },

  // 手指离开
  handleRecordStop: function(e) {
    console.log(e.touches.length)
    if (e.touches.length == 0) {
      console.log("---------------------离开按钮")
      // TODO 语音提示，录音结束
      if (this.data.ifSendMsgRecord) {
        app.textToSpeech('录音结束').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
      } else {
        app.textToSpeech('您取消了发送').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
      }
      recorderManager.stop() //结束录音
      this.setData({
        is_recording: false
      })
    }
  },

  // 手指移动
  handleTouchMove: function(event) {
    // console.log("滑动中########")
    //计算垂直滑动距离
    if (event.touches[0].clientY <= this.data.height * 0.73 && this.data.cancelTipTextRecord != "松开 取消") {
      this.setData({
        ifSendMsgRecord: false,
        cancelTipTextRecord: "松开 取消"
      })
      // TODO 语音提示 现在松手即可取消发送
      app.textToSpeech('现在松手即可取消发送').then((res) => {
        audioPlayer.src = res
        audioPlayer.play()
      })
    } else if (event.touches[0].clientY > this.data.height * 0.73 && this.data.cancelTipTextRecord != "滑动到此处松手取消发送") {
      this.setData({
        ifSendMsgRecord: true,
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })
      // TODO 语音提示 现在松手即可发送
      app.textToSpeech('现在松手即可发送').then((res) => {
        audioPlayer.src = res
        audioPlayer.play()
      })
    }
  },

  /**
   * 播放聊天消息
   */
  playMsg: function(event) {
    const key = event.target.dataset.key
    // console.log(key)

    if (!audioPlayer.paused) {
      audioPlayer.stop()
    }

    const list = this.data.chatMsgList;
    let pause;
    let src;

    for (let index = 0; index < list.length; index++) {
      if (list[index].id != key) {
        list[index].playing = false
      } else {
        if (list[index].playing == true) {
          list[index].playing = false
          pause = true
        } else {
          list[index].playing = true
          pause = false
          src = list[index].content
        }
      }
    }

    if (pause) {
      this.data.isPlayingMsg = false,
        this.setData({
          chatMsgList: list
        })
      return
    } else {
      this.data.isPlayingMsg = true,
        this.setData({
          chatMsgList: list
        })
    }
    console.log(src)
    audioPlayer.src = src
    audioPlayer.play()
  },

  /**
   * 加载聊天消息
   */
  loadMsg: function() {
    const that = this;
    requestUtil.post(API.GET_CHAT_LIST, {
      'appointmentId': that.id,
      'pageSize': this.data.pageSize,
      'currentPage': this.data.nextPage
    }).then(res => {
      console.log(res)
      var chatMsgList = that.data.chatMsgList;
      // 第一次加载重置 chatList
      if (that.data.nextPage == 1) {
        chatMsgList = []
      }
      res.data.list.forEach((value) => {
        if (value.fromUserOpenId == app.globalData.openId) {
          value.side = "right"
        } else {
          value.side = "left"
        }
        value.content = API.FILE_DOWNLOAD + "?fileName=" + value.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT
        value.msgLength = Math.floor(value.duration / 1000)
        value.playing = false
        chatMsgList.unshift(value)
      })


      that.data.nextPage = that.data.nextPage + 1
      if (that.data.nextPage == 2) {
        that.setData({
          toMsgIndex: chatMsgList.length > 0 ? 'msg' + String(chatMsgList.length - 1) : 'msg0',
          chatMsgList: chatMsgList,
          pageCount: res.data.pageCount,
        })
      } else {
        that._freshing = false
        that.setData({
          toMsgIndex: 'msgxxx',
          triggered: false,
          chatMsgList: chatMsgList,
          pageCount: res.data.pageCount,
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * socket传来的消息
   */
  onMessage: function(data) {
    console.log("handle 页收到如下消息")
    console.log(data)
    var msg = JSON.parse(data.data)
    if (msg.message_property == 'chat') {
      let list = this.data.chatMsgList
      msg.data.side = 'left'
      msg.data.msgLength = Math.floor(msg.data.duration / 1000)
      msg.data.playing = false
      msg.data.content = API.FILE_DOWNLOAD + "?fileName=" + msg.data.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_CHAT
      list.push(msg.data)
      this.setData({
        chatMsgList: list,
        toMsgIndex: 'msg' + String(list.length - 1)
      })
    }
  },

  /**
   * 下拉刷新
   */
  // 自定义下拉刷新被触发
  onRefresh() {
    if (this._freshing) return
    this._freshing = true
    console.log('下拉刷新。。。')
    if (this.data.nextPage <= this.data.pageCount) {
      console.log("加载更多历史消息中。。。")
      this.loadMsg()
    } else {
      this.setData({
        triggered: false,
      })
      this._freshing = false
      console.log("没有更多历史消息")
    }
  },

  onPulling(e) {
    console.log('onPulling:', e)
  },

  onRestore(e) {
    console.log('onRestore:', e)
  },

  onAbort(e) {
    console.log('onAbort', e)
  },
})